# -*- coding: utf-8 -*-
# @Time    : 2024/11/7 下午1:56
# @Author  : xiaowanzi
# @File    : mail_tools.py
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart


class SendEmai(object):
    def __init__(self, receivers):
        mail_host = "smtp.waibao.cntaiping.com"  # SMTP服务器
        mail_user = "szsm.liuyt"  # 用户名
        mail_pass = "Taiping88"  # 密码
        sender = "szsm.liuyt@waibao.cntaiping.com"  # 发件人邮箱
        file_path = os.path.dirname(os.path.dirname(__file__)) + '\\report\\test_result.html'
        title = '自动化测试结果'  # 邮件主题
        mail_body = "查看测试报告请下载附件！！！"
        message = MIMEMultipart()
        message['From'] = "{}".format(sender)
        message['To'] = ",".join(receivers)
        message['Subject'] = title
        msgtext = MIMEText(mail_body, _subtype='plain', _charset='utf-8')
        message.attach(msgtext)  # 添加主邮件主体内容
        # 添加一个HTML文本附件
        ff = open(file_path, 'rb')
        att = MIMEText(ff.read(), 'base64', 'utf-8')
        # 附件设置内容类型，设置为二进制流
        att["Content-Type"] = 'application/octet-stream'
        # 设置附件头，添加文件名
        att["Content-Disposition"] = 'attachment; filename="test_result.html"'
        # 解决中文附件名乱码问题
        # att.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', basename))
        message.attach(att)
        ff.close()
        try:
            smtpObj = smtplib.SMTP(mail_host, 25)
            smtpObj.login(mail_user, mail_pass)
            smtpObj.sendmail(sender, receivers, message.as_string())  # 发送
            print("邮件已成功发送")
            smtpObj.quit()
        except smtplib.SMTPException as e:
            print(e)


if __name__ == "__main__":
    # li = ["szsm.liuyt@waibao.cntaiping.com", "chenzy01@fsc.cntaiping.com", "zenglw@fsc.cntaiping.com"]
    li = ["szsm.liuyt@waibao.cntaiping.com", "chenzy01@fsc.cntaiping.com"]
    SendEmai(li)

